﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

using Seven.Entity;
using Seven.EntityBasic;
using Seven.DataModel.ViewModels.DeskModuleAbout;
using Seven.Tools.Extension;
using Seven.Tools.Helper;

namespace Seven.Service.Powerful
{
    public partial class SysDeskModuleService
    {
        #region 获取ViewModel

        /// <summary>
        /// 获取新的桌面模块模型
        /// </summary>
        /// <returns></returns>
        public DeskModuleModel GetNewModel()
        {
            var model = new DeskModuleModel();
            model.Location = DeskModuleLocation.左边;
            model.ControlType = DeskModuleControlType.用户可选;
            model.Size = 8;
            model.Height = 250;
            model.MenuName = "无关联";
            model.ReceiveMessage = true;
            model.IsLimited = true;

            return model;
        }

        /// <summary>
        /// 根据主键ID获取供编辑的数据模型
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        public DeskModuleModel GetEditModel(int id)
        {
            using (var unit = DbFactory.UnitOfWork)
            {
                var rep = unit.SysDeskModule;
                var model = rep.GetEditModelByID(id);
                model.MenuName = model.MenuID == 0 ? "无关联" : model.MenuName;

                return model;
            }
        }

        #endregion

        #region 提供json数据

        /// <summary>
        /// 获取指定位置的桌面模块列表数据
        /// </summary>
        /// <param name="location">位置，值可以是 left 或者 right</param>
        /// <returns></returns>
        public JsonResult DeskModuleGrid(string location)
        {
            using (var unit = DbFactory.UnitOfWork)
            {
                DeskModuleLocation l = location.Equals("left", StringComparison.InvariantCultureIgnoreCase) ? DeskModuleLocation.左边 : DeskModuleLocation.右边;
                var data = unit.SysDeskModule.DeskModuleGrid(l);
                return new DataResult(data).SerializeToJsonResult(true);
            }
        }

        /// <summary>
        /// 一次性获取桌面模块列表数据，返回的数据中以left和right属性区分。
        /// </summary>
        /// <returns></returns>
        public JsonResult DeskModuleJsonForOnce()
        {
            using (var unit = DbFactory.UnitOfWork)
            {
                var rep = unit.SysDeskModule;
                var data = rep.DeskModuleGrid(null);
                var left = data.Where(w => w.Location == DeskModuleLocation.左边);
                var right = data.Where(w => w.Location == DeskModuleLocation.右边);
                return new DataResult(new { left = left, right = right }).SerializeToJsonResult(true);
            }
        }

        /// <summary>
        /// 提供控制类型json数据
        /// </summary>
        /// <returns></returns>
        public JsonResult ControlTypeJson()
        {
            var Types = EnumHelper.GetEnumItems<DeskModuleControlType>(typeof(DeskModuleControlType));

            return new DataResult(Types.Select(s => new { s.Value, s.Text })).SerializeToJsonResult();
        }

        /// <summary>
        /// 提供位置json数据
        /// </summary>
        /// <returns></returns>
        public JsonResult LocationJson()
        {
            var Types = EnumHelper.GetEnumItems<DeskModuleLocation>(typeof(DeskModuleLocation));

            return new DataResult(Types.Select(s => new { s.Value, s.Text })).SerializeToJsonResult();
        }

        #endregion

        #region CUD操作

        /// <summary>
        /// 添加桌面模块
        /// </summary>
        /// <param name="entity">桌面模块实体</param>
        /// <param name="effect">是否立即生效</param>
        /// <returns>操作结果</returns>
        private OperationResult Insert(SysDeskModule entity, bool effect)
        {
            using (var unit = DbFactory.UnitOfWork)
            {
                var rep = unit.SysDeskModule;

                try
                {
                    unit.BeginTransaction();
                    rep.EntityAdded(entity);

                    var msg = new string[] { "添加成功!", "添加失败!" };
                    var result = new OperationResult(unit.Commit() > 0, msg);
                    if (effect && result.Success)
                    {
                        unit.SysUserDeskModule.InitUserDeskModule(entity.ID);
                    }
                    return result;
                }
                catch (DataAccessException ex)
                {
                    unit.Rollback();
                    throw ExceptionHelper.ThrowServiceException(ex.Message);
                }
            }
        }

        /// <summary>
        /// 更新桌面模块
        /// </summary>
        /// <param name="entity">桌面模块实体</param>
        /// <param name="effect">是否立即生效</param>
        /// <returns>操作结果</returns>
        private OperationResult Update(SysDeskModule entity, bool effect)
        {
            using (var unit = DbFactory.UnitOfWork)
            {
                var rep = unit.SysDeskModule;

                try
                {
                    unit.BeginTransaction();
                    rep.EntityModified(entity);

                    var msg = new string[] { "更新成功!", "更新失败!" };
                    var result = new OperationResult(unit.Commit() > 0, msg);
                    if (effect && result.Success)
                    {
                        unit.SysUserDeskModule.ResetUserDeskModule(entity.ID, entity.ControlType == DeskModuleControlType.用户必选, effect && entity.IsLimited);
                    }
                    return result;
                }
                catch (DataAccessException ex)
                {
                    unit.Rollback();
                    throw ExceptionHelper.ThrowServiceException(ex.Message);
                }
            }
        }

        /// <summary>
        /// 保存桌面模块
        /// </summary>
        /// <param name="model">桌面模块数据模型</param>
        /// <returns>操作结果</returns>
        public JsonResult SaveDeskModule(DeskModuleModel model)
        {
            if (model.ID == 0)
            {
                SysDeskModule entity = model.CopyTo<SysDeskModule>();
                return this.Insert(entity, (model.EffectUser && model.IsLimited)).SerializeToJsonResult();
            }
            else
            {
                SysDeskModule entity = this.GetByKey(model.ID);

                entity.Name = model.Name;
                entity.Location = model.Location;
                entity.SortNumber = model.SortNumber;
                entity.ControlType = model.ControlType;
                entity.Size = model.Size;
                entity.Height = model.Height;
                entity.MenuID = model.MenuID;
                entity.ActionName = model.ActionName;
                entity.IsDisabled = model.IsDisabled;
                entity.ReceiveMessage = model.ReceiveMessage;
                entity.IsLimited = model.IsLimited;
                entity.Remark = model.Remark;

                return this.Update(entity, model.EffectUser).SerializeToJsonResult();
            }
        }

        /// <summary>
        /// 删除桌面模块
        /// </summary>
        /// <param name="id">桌面模块ID</param>
        /// <returns></returns>
        public JsonResult RemoveDeskModule(int id)
        {
            using (var unit = DbFactory.UnitOfWork)
            {
                var rep = unit.SysDeskModule;
                try {
                    var entity = this.GetByKey(id);
                    if (entity == null) { return new OperationResult(false, true, "桌面模块不存在！").SerializeToJsonResult(); }

                    unit.BeginTransaction();
                    rep.EntityDeleted(entity);

                    var msg = new string[] { "删除成功!", "删除失败!" };
                    var result = new OperationResult(unit.Commit() > 0, msg);
                    if (result.Success)
                    {
                        unit.SysUserDeskModule.RemoveUserDeskModule(entity.ID);
                    }
                    return result.SerializeToJsonResult();
                }
                catch (DataAccessException ex) {
                    unit.Rollback();
                    throw ExceptionHelper.ThrowServiceException(ex.Message);
                }
            }
        }

        #endregion
    }
}
